function runTasksConcurrently(tasks, concurrency) {
    let activePromises = [];
    let results = [];

    function executeTask() {
        if (tasks.length > 0 && activePromises.length < concurrency) {
            const task = tasks.shift();
            activePromises.push(
                new Promise((resolve, reject) => {
                    Promise.resolve(task()).then(resolve).catch(reject);
                })
                    .then((result) => {
                        results.push(result);
                        activePromises.shift(); // 任务完成，从活跃列表中移除
                        executeTask(); // 继续执行下一个任务
                    })
                    .catch((error) => {
                        results.push(error);
                        activePromises.shift(); // 任务失败，从活跃列表中移除
                        executeTask(); // 继续执行下一个任务
                    }),
            );
        }
    }

    executeTask(); // 立即开始执行任务

    return new Promise((resolve, reject) => {
        if (activePromises.length === 0) {
            resolve(results); // 所有任务都已完成
        } else {
            // 等待所有活跃的任务完成
            Promise.all(activePromises)
                .then(() => {
                    resolve(results);
                })
                .catch(reject);
        }
    });
}

// 使用示例
const tasks = [
    // () => setTimeout(() => Promise.resolve("Task 1"), 1000),
    // () => setTimeout(() => Promise.resolve("Task 2"), 2000),
    // () => setTimeout(() => Promise.resolve("Task 3"), 3000),
    // () => setTimeout(() => Promise.resolve("Task 4"), 500),

    new Promise((resolve) => setTimeout(() => resolve("Task1 "), 1000)),
    new Promise((resolve) => setTimeout(() => resolve("Task2 "), 2000)),
    new Promise((resolve) => setTimeout(() => resolve("Task3 "), 3000)),
    new Promise((resolve) => setTimeout(() => resolve("Task4 "), 500)),
    // () => Promise.resolve("Task 2"),
    // () => Promise.resolve("Task 3"),
];
const concurrency = 2;

runTasksConcurrently(tasks, concurrency)
    .then((results) => {
        console.log("All tasks completed with results:", results);
    })
    .catch((error) => {
        console.error("An error occurred:", error);
    });
